﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using Lib.Approval;
using Lib.Helper;
using MSIACCSL2.CoaServices;
using MSIACCSL2.Command;
using MSIACCSL2.SupplierServices;
using MSIACCSL2.Views.Supplier;
using WcfService1.DTO;
using GetListByCriteriaCompletedEventArgs = MSIACCSL2.SupplierServices.GetListByCriteriaCompletedEventArgs;
using GetListCompletedEventArgs = MSIACCSL2.SupplierServices.GetListCompletedEventArgs;
using SaveCompletedEventArgs = MSIACCSL2.SupplierServices.SaveCompletedEventArgs;

namespace MSIACCSL2.ViewModels
{
    public class SupplierViewModel : ViewModelBase
    {
        #region Delegates

        public delegate void Completed(Object param);

        #endregion

        private static string OrderType;
        private static string PropertySort;
        public static Mode mode;
        private static SupplierDTO _Supplier;
        private static Add frmAdd;
        public static Completed OnSearchCompleted;
        private readonly CoaServicesClient CoaClient;
        private readonly SupplierServicesClient client;
        private readonly ValidationHandler validationHandler;
        private int CurrentPage;
        private ObservableCollection<int> Pages;
        private ObservableCollection<CoaDTO> _COAs;
        private bool _IsBusy;
        private PagedCollectionView _Suppliers;
        private List<string> _errors;
        private Visibility _messageVisibility;
        private PagedCollectionView _pageSources;
        private ObservableCollection<SupplierDTO> _parents;
        private static Search frmSearch;
        private Dictionary<string, object> criteria;
        private string expression;


        public SupplierViewModel()
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                client = new SupplierServicesClient();
                CoaClient = new CoaServicesClient();
                OnPageChanged = new DelegateCommand(PageIndexChanged, CanPageIndexChanged);
                Save = new DelegateCommand(SaveSupplier, CanSave);
                New = new DelegateCommand(NewSupplier, CanNew);
                Edit = new DelegateCommand(EditSupplier, CanEdit);
                Unload = new DelegateCommand(Release, CanUnload);
                SearchCommand = new DelegateCommand(SearchSupplier, CanSearch);
                SearchResultCommand = new DelegateCommand(SearchResult, CanSearchResult);
                SearchSupplierCommand = new DelegateCommand(SearchSupplierByName, CanSearch);
                validationHandler = new ValidationHandler();
                MessageVisibility = Visibility.Collapsed;

                if (mode == Mode.Edit || mode == Mode.Search || mode == Mode.Add)
                {
                    GetCOAList();
                }
                else
                {
                    GetList(1, null);
                }
            }
        }

        public PagedCollectionView Suppliers
        {
            get { return _Suppliers; }

            private set
            {
                if (Suppliers == value) return;
                _Suppliers = value;
                int i = (CurrentPage*30);
                foreach (object Supplier in Suppliers)
                {
                    i += 1;

                    ((SupplierDTO) Supplier).No = i;
                }
                FirePropertyChanged("Suppliers");
                Suppliers.CollectionChanged += Supplier_CollectionChanged;
            }
        }


        public PagedCollectionView PageSources
        {
            get { return _pageSources; }
            private set
            {
                if (PageSources == value) return;
                _pageSources = value;
                FirePropertyChanged("PageSources");
            }
        }

        public ObservableCollection<CoaDTO> COAs
        {
            get { return _COAs; }
            private set
            {
                if (COAs == value) return;
                _COAs = value;
                FirePropertyChanged("COAs");
            }
        }


        public bool IsBusy
        {
            get { return _IsBusy; }
            internal set
            {
                _IsBusy = value;
                FirePropertyChanged("IsBusy");
            }
        }


        public long RecordCount { get; set; }

        //Buat binding ke child form waktu mau edit
        public static SupplierDTO Supplier
        {
            get { return _Supplier; }
            private set
            {
                if (Supplier == value) return;
                _Supplier = value;
                FirePropertyChanged2("Supplier");
            }
        }


        public ICommand OnPageChanged { get; set; }
        public ICommand Save { get; set; }
        public ICommand New { get; set; }
        public ICommand Edit { get; set; }
        public ICommand Unload { get; set; }
        public ICommand SearchCommand { get; set; }
        public ICommand SearchResultCommand { get; set; }
        public ICommand SearchSupplierCommand { get; set; }

        public List<string> Errors
        {
            get { return _errors; }
            private set
            {
                if (Errors == value) return;
                _errors = value;
                FirePropertyChanged("Errors");
            }
        }

        public Visibility MessageVisibility
        {
            get { return _messageVisibility; }
            private set
            {
                if (MessageVisibility == value) return;
                _messageVisibility = value;
                FirePropertyChanged("MessageVisibility");
            }
        }

        public string this[string columnName]
        {
            get
            {
                if (validationHandler.BrokenRuleExists(columnName))
                {
                    return validationHandler[columnName];
                }
                return null;
            }
        }

        public void Complete(Object param)
        {
            OnSearchCompleted(param);
        }

        private void Supplier_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (((PagedCollectionView) sender).SortDescriptions.Count > 0)
            {
                if (((PagedCollectionView) sender).SortDescriptions[0].PropertyName.ToLower() == "no") return;

                PropertySort = ((PagedCollectionView) sender).SortDescriptions[0].PropertyName;
                if (string.IsNullOrEmpty(OrderType))
                {
                    OrderType = "ASC";
                }
                else
                {
                    OrderType = OrderType == "ASC" ? OrderType = "DESC" : OrderType = "ASC";
                }
                GetList(1, PropertySort);
            }
        }


        public void SaveSupplier(Object supplier)
        {
            Supplier = (SupplierDTO) supplier;
            Validate();
            if (Errors.Count > 0) return;
            Supplier.created_by = GlobalVar.User.UserID;
            Supplier.modified_by = GlobalVar.User.UserID;
            client.SaveCompleted += client_SaveSupplierCompleted;
            client.SaveAsync(Supplier,mode.ToString());
        }


        private void client_SaveSupplierCompleted(object sender, SaveCompletedEventArgs e)
        {
            client.SaveCompleted -= client_SaveSupplierCompleted;
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }else
            {
                MessageBox.Show("Success");
                frmAdd.DialogResult = true;
                Refresh();
            }
        }


        public void GetList(int? page, string sortProp)
        {
            IsBusy = true;
            client.GetListCompleted += client_GetListCompleted;
            client.GetListAsync(page ?? 1, sortProp, OrderType);
        }

        private void client_GetListCompleted(object sender, GetListCompletedEventArgs e)
        {
            RecordCount = e.recordCount;
            if (PageSources == null) CreatePageNumber();
            client.GetListCompleted -= client_GetListCompleted;
            Suppliers = new PagedCollectionView(e.Result);
            IsBusy = false;
            Complete(this);
        }

        public void GetCOAList()
        {
            CoaClient.GetAllCoaCompleted += CoaClient_GetAllCoaCompleted;
            CoaClient.GetAllCoaAsync();
        }

        private void CoaClient_GetAllCoaCompleted(object sender, GetAllCoaCompletedEventArgs e)
        {
            CoaClient.GetAllCoaCompleted -= CoaClient_GetAllCoaCompleted;
            COAs = e.Result;
        }

        private void NewSupplier(Object param)
        {
            mode = Mode.Add;
            Supplier = new SupplierDTO();
            frmAdd = new Add();
            frmAdd.Show();
        }


        public static void EditSupplier(Object param)
        {
            mode = Mode.Edit;
            Supplier = (SupplierDTO) param;
            frmAdd = new Add();
            frmAdd.Show();
        }


        private void SearchSupplier(Object param)
        {
            mode = Mode.Search;
            Supplier = new SupplierDTO();
            frmSearch = new Search();
            frmSearch.Show();
        }


        private void SearchResult(Object param)
        {
            criteria = new Dictionary<string, object>();

            foreach (PropertyInfo prop in Supplier.GetType().GetProperties())
            {
                if (prop.PropertyType == typeof (Decimal))
                {
                    if ((Decimal) prop.GetValue(Supplier, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Int32))
                {
                    if ((Int32) prop.GetValue(Supplier, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Int64))
                {
                    if ((Int64) prop.GetValue(Supplier, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Double))
                {
                    if ((Double) prop.GetValue(Supplier, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (String))
                {
                    if (String.IsNullOrEmpty((String) prop.GetValue(Supplier, null))) continue;
                }
                if (prop.PropertyType == typeof (DateTime))
                {
                    if (prop.GetValue(Supplier, null).ToString().Contains("0001")) continue;
                }
                if (prop.GetValue(Supplier, null) == null) continue;
                if (prop.PropertyType.Name == "No") continue;

                if (prop.PropertyType.Name.ToLower().Contains("dto"))
                {
                    foreach (PropertyInfo propertyInfo in prop.GetValue(Supplier, null).GetType().GetProperties())
                    {
                        if (propertyInfo.Name.ToLower().Contains("id") || propertyInfo.Name.ToLower().Contains("kode") ||
                            propertyInfo.Name.ToLower().Contains("serial") ||
                            propertyInfo.Name.ToLower().Contains("code"))
                        {
                            criteria.Add(prop.Name, propertyInfo.GetValue(prop.GetValue(Supplier, null), null));
                            break;
                        }
                    }
                }
                else
                {
                    criteria.Add(prop.Name, prop.GetValue(Supplier, null));
                }
            }

            expression = string.Empty;
            if (frmSearch.rbOr.IsChecked ?? false) expression = "OR";
            else expression = "AND";
            SupplierSearch(criteria, expression,1);
        }

        private void SupplierSearch(Dictionary<String, Object> criteria, string expression,int page)
        {
            frmSearch.DialogResult = true;
            IsBusy = true;
            Complete(this);
            client.GetListByCriteriaCompleted += client_GetListByCriteriaCompleted;
            client.GetListByCriteriaAsync(criteria, expression, page);
        }

        private void client_GetListByCriteriaCompleted(object sender, GetListByCriteriaCompletedEventArgs e)
        {
            client.GetListByCriteriaCompleted -= client_GetListByCriteriaCompleted;
            Suppliers = new PagedCollectionView(e.Result);
            if (RecordCount != e.recordCount)
            {
                RecordCount = e.recordCount;
                CreatePageNumber();
            }
            IsBusy = false;
        }


        private void CreatePageNumber()
        {
            Pages = new ObservableCollection<int>();
            for (int i = 0; i < RecordCount; i++)
            {
                Pages.Add(i);
            }
            PageSources = new PagedCollectionView(Pages);
        }


        private void PageIndexChanged(Object pageIndex)
        {
            //Jika Pertama kali jangan di Getlagi
            Supplier = null;
            if (Suppliers != null && CurrentPage != (int) pageIndex)
            {
                CurrentPage = (int) pageIndex;
                if (mode == Mode.Search)
                    SupplierSearch(criteria, expression, (int)pageIndex + 1);
                else if (String.IsNullOrEmpty(PropertySort))
                    GetList((int) pageIndex + 1, null);
                else GetList((int) pageIndex + 1, PropertySort);
            }
        }


        public bool CanPageIndexChanged(Object param)
        {
            return true;
        }


        public bool CanSave(Object param)
        {
            return true;
        }


        public bool CanNew(Object param)
        {
            return true;
        }

        public bool CanEdit(Object param)
        {
            return true;
        }


        public bool CanUnload(Object param)
        {
            return true;
        }


        public bool CanSearch(Object param)
        {
            return true;
        }

        public bool CanSearchResult(Object param)
        {
            return true;
        }


        public void Release(Object param)
        {
            param = null;
            Supplier = null;
            OrderType = null;
            PropertySort = null;
            mode = Mode.Idle;
        }


        public void Refresh()
        {
            if (Suppliers == null)
                GetList(1, null);
            else
                Complete(this);
        }


        public void Validate(string error = null)
        {
            Errors = new List<string>();
            if (string.IsNullOrEmpty(Supplier.SupplierName))
                Errors.Add("Suppliername tidak boleh kosong");
            if (!string.IsNullOrEmpty(error))
                Errors.Add(error);

            if (Errors.Count > 0)
            {
                MessageVisibility = Visibility.Visible;
            }
            else
            {
                MessageVisibility = Visibility.Collapsed;
            }
        }


        public void SearchSupplierByName(Object param)
        {
            if (param == null) return;
            client.GetSupplierListCompleted += client_GetSupplierListCompleted;
            client.GetSupplierListAsync(param.ToString());
        }

        private void client_GetSupplierListCompleted(object sender, GetSupplierListCompletedEventArgs e)
        {
            client.GetSupplierListCompleted -= client_GetSupplierListCompleted;
            Suppliers = new PagedCollectionView(e.Result);
        }
    }


    public class SupplierWrapViewModel : ViewModelBase
    {
        private readonly SupplierServicesClient client;

        public SupplierWrapViewModel()
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                EditCommand = new DelegateCommand(Edit, CanEditCommand);
                DeleteCommand = new DelegateCommand(Delete, CanDeleteCommand);
                client = new SupplierServicesClient();
            }
        }


        public ICommand EditCommand { get; set; }
        public ICommand DeleteCommand { get; set; }


        public bool CanEditCommand(Object param)
        {
            return true;
        }

        public bool CanDeleteCommand(Object param)
        {
            return true;
        }


        public void Edit(Object param)
        {
            SupplierViewModel.EditSupplier(param);
        }

        public void Delete(Object param)
        {
            DeleteConfirmation deleteConfirmation = new DeleteConfirmation();
            deleteConfirmation.Show();
            EventAggregator.RegisterMessage("ApprovalSucceeded", (x) =>
            {
                deleteConfirmation.Close();
                client.DeleteCompleted += client_DeleteCompleted;
                client.DeleteAsync((SupplierDTO)param);
            });
        }

        private void client_DeleteCompleted(object sender, SupplierServices.DeleteCompletedEventArgs e)
        {
          
            client.DeleteCompleted -= client_DeleteCompleted;
            if (e.Result)
            {
                MessageBox.Show("Delete Success!");
            }
            else
            {
                MessageBox.Show("Data sudah link ke transaksi lain, tidak boleh dihapus!");
            }
            SupplierViewModel.mode = Mode.Idle;
            var VM = new SupplierViewModel();
        }
    }


    // add by kamal to convert detail supplier
    // address
    public class SupplierAddressConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null)
            {
                return ((dynamic) value).Address;
            }
            else
            {
                return string.Empty;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }

    // country
    // address
    public class SupplierCountryConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null)
            {
                return ((dynamic) value).Country;
            }
            else
            {
                return string.Empty;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }

    // supplier attn / contact person
    public class SupplierContactPersonConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null)
            {
                return ((dynamic) value).ContactPerson;
            }
            else
            {
                return string.Empty;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }

    // supplier telp
    public class SupplierTelpConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null)
            {
                return ((dynamic) value).Telp;
            }
            else
            {
                return string.Empty;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }

    // supplier fax
    public class SupplierFaxConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null)
            {
                return ((dynamic) value).Fax;
            }
            else
            {
                return string.Empty;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}